package com.luojialong.onlineJudge.aop;


import com.luojialong.onlineJudge.annotation.AuthCheck;
import com.luojialong.onlineJudge.common.ErrorCode;
import com.luojialong.onlineJudge.exception.BusinessException;
import com.luojialong.onlineJudge.model.entity.User;
import com.luojialong.onlineJudge.service.UserService;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

@Aspect
@Component
public class PermissionCheckHandle {

    @Resource
    private UserService userService;


    @Around("@annotation(permissionCheck)")
    public Object doHandle(ProceedingJoinPoint joinPoint, AuthCheck permissionCheck) throws Throwable {
        //获得最低权限的用户级别
        String leastRole = permissionCheck.mustRole();
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();

        HttpServletRequest request = ((ServletRequestAttributes) requestAttributes).getRequest();

        User loginUser = userService.getLoginUser(request);

        String role = loginUser.getUserRole();

        if (leastRole.equals(role)) {
            throw new BusinessException(ErrorCode.FORBIDDEN_ERROR, "你没有此权限");
        }
        return joinPoint.proceed();
    }

}
